package com.jmemoir.base.common.handle;

import com.jmemoir.base.common.dto.Result;
import com.jmemoir.base.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author Tellsea
 * @date 2023/8/2
 */
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public Result<String> handleServiceException(ServiceException e) {
        return Result.fail(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(BindException.class)
    public Result<String> handleBindException(BindException e) {
        int errorCount = e.getErrorCount();
        List<ObjectError> allErrors = e.getAllErrors();
        List<String> errors = allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        String joinedErrors = String.join(", ", errors);
        return Result.fail(String.format("共有%d个参数格式错误，分别是：%s", errorCount, joinedErrors));
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result<String> handleConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violationSet = e.getConstraintViolations();
        List<String> collect = violationSet.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
        String joinedErrors = String.join(", ", collect);
        return Result.fail(joinedErrors);
    }

    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        e.printStackTrace();
        return Result.fail(e.getMessage());
    }
}